let wordCloudData = null; // 用于缓存词云数据

document.addEventListener('DOMContentLoaded', function() {
  // 定义DOM元素
  const timelineSection = document.getElementById('timelineSection');
  const wordCloudSection = document.getElementById('wordCloudSection');
  const govSection = document.getElementById('govSection');
  const policyTimelineLink = document.getElementById('policyTimeline');
  const policyWordCloudLink = document.getElementById('policyWordCloud');
  const govPoliciesLink = document.getElementById('govPolicies');
  
  // 预加载词云数据
  function preloadWordCloudData() {
    // 检查本地存储中是否有缓存的词云数据
    const cachedData = localStorage.getItem('wordCloudData');
    const cacheTimestamp = localStorage.getItem('wordCloudTimestamp');
    
    // 如果有缓存且缓存时间在24小时内，使用缓存数据
    if (cachedData && cacheTimestamp) {
      const now = new Date().getTime();
      const cacheTime = parseInt(cacheTimestamp);
      // 缓存有效期为24小时
      if (now - cacheTime < 24 * 60 * 60 * 1000) {
        console.log('使用缓存的词云数据');
        wordCloudData = JSON.parse(cachedData);
        return;
      }
    }
    
    // 否则从API获取数据
    fetch('/api/word_frequency')
      .then(response => response.json())
      .then(data => {
        // 存储数据到全局变量
        wordCloudData = data.map(item => ({
          name: item.词语,
          value: item.频次
        })).slice(0, 100); // 只使用前100个高频词，减少渲染压力
        
        // 将数据缓存到localStorage
        localStorage.setItem('wordCloudData', JSON.stringify(wordCloudData));
        localStorage.setItem('wordCloudTimestamp', new Date().getTime().toString());
      })
      .catch(error => console.error('获取词频数据失败:', error));
  }

  // 在文档加载完成时立即预加载词云数据
  preloadWordCloudData();
  
  // 为导航链接添加事件监听器
  policyTimelineLink.addEventListener('click', function(e) {
    e.preventDefault();
    document.querySelectorAll('.main-header-link').forEach(el => el.classList.remove('is-active'));
    this.classList.add('is-active');
    timelineSection.style.display = 'block';
    wordCloudSection.style.display = 'none';
    govSection.style.display = 'none';
  });
  
  policyWordCloudLink.addEventListener('click', function(e) {
    e.preventDefault();
    document.querySelectorAll('.main-header-link').forEach(el => el.classList.remove('is-active'));
    this.classList.add('is-active');
    timelineSection.style.display = 'none';
    wordCloudSection.style.display = 'block';
    govSection.style.display = 'none';
    
    // 如果词云图表尚未初始化，则初始化它
    if (!wordCloudChart) {
      createWordCloud();
    }
  });
  
  govPoliciesLink.addEventListener('click', function(e) {
    e.preventDefault();
    document.querySelectorAll('.main-header-link').forEach(el => el.classList.remove('is-active'));
    this.classList.add('is-active');
    timelineSection.style.display = 'none';
    wordCloudSection.style.display = 'none';
    govSection.style.display = 'block';
  });
  
  // 获取政策数据
  let policiesData = [];
  fetch('/api/gov_policies')
    .then(response => response.json())
    .then(data => {
      policiesData = data;
      renderPolicyTimeline(policiesData);
      renderGovPolicies(policiesData.filter(policy => policy.is_gov === 1));
    })
    .catch(error => console.error('获取政策数据失败:', error));
  
  // 渲染政策时间线
  function renderPolicyTimeline(policies) {
    const timelineSection = document.querySelector('.policy-timeline-container');
    
    // 清空现有内容
    timelineSection.innerHTML = '';
    
    // 创建新的时间轴结构
    timelineSection.innerHTML = `
      <div class="shell">
        <div class="header">
          <h2 class="title">新能源汽车政策时间线</h2>
        </div>
        <div class="timeline"></div>
      </div>
    `;
    
    // 按照发布时间排序政策
    policies.sort((a, b) => new Date(a.发布时间) - new Date(b.发布时间));
    
    // 提取所有不同的年份和月份，按时间分组
    const timeGroups = {};
    policies.forEach(policy => {
      const date = new Date(policy.发布时间);
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const timeKey = `${year}-${String(month).padStart(2, '0')}`;
      
      if (!timeGroups[timeKey]) {
        timeGroups[timeKey] = {
          display: `${year}年${month}月`,
          policies: []
        };
      }
      
      timeGroups[timeKey].policies.push(policy);
    });
    
    // 渲染时间轴项目
    const timeline = document.querySelector('.timeline');
    const timeKeys = Object.keys(timeGroups).sort();
    
    timeKeys.forEach((timeKey, index) => {
      const group = timeGroups[timeKey];
      const representativePolicy = group.policies[0]; // 用第一个政策作为代表
      const date = new Date(representativePolicy.发布时间);
      const formattedDate = `${date.getFullYear()}年${date.getMonth() + 1}月`;
      
      const item = document.createElement('div');
      item.className = 'item';
      item.dataset.text = formattedDate;
      
      // 创建内容
      const content = document.createElement('div');
      content.className = 'content';
      
      // 创建政策卡片作为主要内容
      content.innerHTML = `
        <div class="policy-timeline-card">
          <h2 class="content-title">${formattedDate}</h2>
          <div class="policy-count">${group.policies.length}项政策</div>
          <p class="content-desc">${representativePolicy.标题}</p>
          <div class="view-all-policies" data-time-key="${timeKey}">查看所有政策</div>
        </div>
      `;
      
      item.appendChild(content);
      timeline.appendChild(item);
      
      // 添加点击事件展开该时期所有政策
      const viewAllButton = content.querySelector('.view-all-policies');
      viewAllButton.addEventListener('click', function() {
        showAllPoliciesForPeriod(timeKey, group.policies);
      });
    });
    
    // 初始化时间轴滚动效果
    initTimelineScrollEffect();
    
    // 添加鼠标滚轮事件来增强交互性
    const timelineContainer = document.querySelector('.shell');
    timelineContainer.addEventListener('wheel', (e) => {
      // 获取所有项目
      const items = document.querySelectorAll('.timeline .item');
      const activeItem = document.querySelector('.timeline .item--active');
      
      if (!activeItem) return;
      
      // 向下滚动时，激活下一个项目
      if (e.deltaY > 0) {
        const nextItem = activeItem.nextElementSibling;
        if (nextItem && nextItem.classList.contains('item')) {
          // 滚动到下一个项目
          nextItem.scrollIntoView({
            behavior: 'smooth',
            block: 'center'
          });
          e.preventDefault(); // 防止页面滚动
        }
      } 
      // 向上滚动时，激活上一个项目
      else if (e.deltaY < 0) {
        const prevItem = activeItem.previousElementSibling;
        if (prevItem && prevItem.classList.contains('item')) {
          // 滚动到上一个项目
          prevItem.scrollIntoView({
            behavior: 'smooth',
            block: 'center'
          });
          e.preventDefault(); // 防止页面滚动
        }
      }
    }, { passive: false });
  }
  
  // 展示某个时期的所有政策
  function showAllPoliciesForPeriod(timeKey, policies) {
    // 创建政策详情弹窗
    const popup = document.createElement('div');
    popup.className = 'policies-popup';
    
    const popupContent = document.createElement('div');
    popupContent.className = 'policies-popup-content';
    
    // 添加关闭按钮
    const closeButton = document.createElement('div');
    closeButton.className = 'close-popup';
    closeButton.innerHTML = '&times;';
    closeButton.addEventListener('click', () => {
      document.body.removeChild(popup);
    });
    
    // 添加标题
    const title = document.createElement('h2');
    title.textContent = `${timeKey.split('-')[0]}年${timeKey.split('-')[1]}月政策列表`;
    
    // 添加政策列表
    const policyList = document.createElement('div');
    policyList.className = 'policy-list';
    
    policies.forEach(policy => {
      const date = new Date(policy.发布时间);
      const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
      
      const policyCard = document.createElement('div');
      policyCard.className = 'popup-policy-card';
      if (policy.is_gov === 1) {
        policyCard.classList.add('important-policy');
      }
      
      policyCard.innerHTML = `
        <div class="policy-card-date">${formattedDate}</div>
        <h3 class="policy-card-title">${policy.标题}</h3>
        <div class="policy-card-link">
          <a href="${policy.链接}" target="_blank" class="content-button status-button">查看详情</a>
        </div>
      `;
      
      policyList.appendChild(policyCard);
    });
    
    popupContent.appendChild(closeButton);
    popupContent.appendChild(title);
    popupContent.appendChild(policyList);
    popup.appendChild(popupContent);
    
    document.body.appendChild(popup);
  }
  
  // 修改时间轴滚动效果函数
  function initTimelineScrollEffect() {
    const items = document.querySelectorAll('.timeline .item');
    
    // 默认激活第一个
    if (items.length > 0) {
      items[0].classList.add('item--active');
    }
    
    // 使用IntersectionObserver代替scroll事件
    const options = {
      root: null, // 使用视口作为根
      rootMargin: '0px',
      threshold: 0.5 // 当元素50%可见时触发
    };
    
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          // 激活当前可见的项目
          entry.target.classList.add('item--active');
        } else if (entry.boundingClientRect.top > 0) {
          // 只有当元素在视口下方才移除激活状态
          entry.target.classList.remove('item--active');
        }
      });
    }, options);
    
    // 观察所有时间轴项目
    items.forEach(item => {
      observer.observe(item);
    });
  }
  
  // 渲染国务院政策
  function renderGovPolicies(govPolicies) {
    const govPolicyCardsContainer = document.querySelector('.gov-policy-cards');
    govPolicyCardsContainer.innerHTML = '';
    
    govPolicies.forEach(policy => {
      const date = new Date(policy.发布时间);
      const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
      
      const policyCard = document.createElement('div');
      policyCard.className = 'policy-card';
      policyCard.innerHTML = `
        <div class="policy-card-date">${formattedDate}</div>
        <h3 class="policy-card-title">${policy.标题}</h3>
        <a href="${policy.链接}" target="_blank" class="content-button status-button">查看政策详情</a>
      `;
      
      govPolicyCardsContainer.appendChild(policyCard);
    });
  }
  
  // 创建词云图表
  let wordCloudChart = null;
  function createWordCloud() {
    // 初始化词云图表
    wordCloudChart = echarts.init(document.getElementById('wordCloudChart'));
    
    // 显示加载中动画
    wordCloudChart.showLoading({
      text: '词云加载中...',
      color: '#3a6df0',
      textColor: '#fff',
      maskColor: 'rgba(0, 0, 0, 0.1)'
    });
    
    // 如果已经有缓存数据，直接使用
    if (wordCloudData) {
      renderWordCloud(wordCloudData);
      return;
    }
    
    // 如果没有缓存数据，从API获取
    fetch('/api/word_frequency')
      .then(response => response.json())
      .then(data => {
        // 转换数据格式为词云所需格式，并限制为前100个词
        const cloudData = data.map(item => ({
          name: item.词语,
          value: item.频次
        })).slice(0, 100);
        
        renderWordCloud(cloudData);
        
        // 更新缓存
        wordCloudData = cloudData;
        localStorage.setItem('wordCloudData', JSON.stringify(wordCloudData));
        localStorage.setItem('wordCloudTimestamp', new Date().getTime().toString());
      })
      .catch(error => {
        console.error('获取词频数据失败:', error);
        wordCloudChart.hideLoading();
        
        // 显示错误信息
        wordCloudChart.setOption({
          title: {
            text: '无法加载词云数据',
            left: 'center',
            top: 'center',
            textStyle: {
              color: '#e1e1e1'
            }
          }
        });
      });
  }
  
  // 专门用于渲染词云的函数
  function renderWordCloud(data) {
    // 配置词云图表
    const option = {
      title: {
        text: '新能源汽车政策关键词词云',
        left: 'center',
        textStyle: {
          color: '#e1e1e1'
        }
      },
      tooltip: {
        show: true,
        formatter: function(params) {
          return params.name + ': ' + params.value;
        }
      },
      series: [{
        type: 'wordCloud',
        shape: 'circle',
        left: 'center',
        top: 'center',
        width: '80%',
        height: '80%',
        right: null,
        bottom: null,
        sizeRange: [12, 60],
        rotationRange: [-45, 45], // 减少旋转角度范围，提高可读性
        rotationStep: 15,
        gridSize: 8,
        drawOutOfBound: false,
        layoutAnimation: false, // 关闭布局动画，提高性能
        textStyle: {
          fontFamily: 'sans-serif',
          fontWeight: 'bold',
          color: function () {
            // 使用预定义的颜色列表，避免随机颜色计算
            const colors = [
              '#3a6df0', '#3a9df0', '#3ad8f0', 
              '#f03a9d', '#f0683a', '#f0c23a',
              '#3af078', '#a63af0', '#f03a3a'
            ];
            return colors[Math.floor(Math.random() * colors.length)];
          }
        },
        emphasis: {
          focus: 'self',
          textStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.3)'
          }
        },
        data: data
      }],
      backgroundColor: 'transparent'
    };
    
    // 隐藏加载中动画
    wordCloudChart.hideLoading();
    
    // 渲染词云图表
    wordCloudChart.setOption(option);
  }
  
  // 窗口大小变化时调整图表大小
  window.addEventListener('resize', function() {
    if (wordCloudChart) {
      wordCloudChart.resize();
    }
  });
}); 